import { $store, $session, $cookie } from "@/utils/store.js";
import $ from "jquery";
import { Message } from "element-ui";
export const linYeCode = "100000";
export const ttIndustryCode = "999999";
import store from "@/store/index";
/* 获取url地址 */
let $getUrlParam = function (name) {
  try {
    const webUrl = window.location.href;
    if (webUrl.indexOf("?") === -1) {
      return "";
    }
    const params = webUrl.split("?")[1];
    const strs = params.split("&");
    const param = {};
    for (let i = 0; i < strs.length; i++) {
      param[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
    const resp = param[name] || "";
    return decodeURI(resp);
  } catch (e) {
    return "";
  }
};
const PAGE_SIZES = [10, 20, 50, 100];
const PAGE_SIZE = PAGE_SIZES[0]; //分页中的每页条数
const urlSystem = "VIDEO-APPLY-SYSTEM"; //system
const urlVideo = "VIDEO-APPLY-VIDEO"; //video
const urlEvent = "VIDEO-APPLY-EVENT"; //event
const videoStreamType = "1"; //默认主子码流类型

window.lookMessageDetail = (id) => {
  $("." + id).removeClass("message-more-new");
};
//封装简写的vue请求
class $v {
  /**
   * @param {type} success: 成功, warn: 提示, warning: 提示, error: 错误; 默认warning; 不区分大小写
   * @param {mess, message} 消息内容; 必选其一
   * @param {data} 消息详情; 可选
   */
  static message(param = {}) {
    if (typeof param === "string") {
      const mess = param;
      param = {
        type: "success",
        mess: mess,
      };
    }
    if (!param.type) {
      param.type = "warning";
    }
    param.type = param.type.toLowerCase();
    if (param.type === "warn") {
      param.type = "warning";
    }
    const duration = 5000;
    const only = new Date().getTime();
    let isVideoMsg = false;
    if (param.data != null && param.data.indexOf("错误详情:") > -1) {
      param.data = param.data.substring(5);
      isVideoMsg = true;
    }
    let ob = {
      type: param.type,
      message: param.mess || String(param.message),
      duration: duration,
      showClose: true,
      customClass:
        `message-new ${param.customClass} message-` +
        param.type +
        "-new" +
        " " +
        only,
    };
    if (isVideoMsg) {
      try {
        var obj = JSON.parse(param.data);
        ob = {
          type: "error",
          message: obj.title,
          duration: duration,
          showClose: true,
          customClass:
            "message-new message-" + param.type + "-new" + " " + only,
        };
        ob.customClass += " message-more-new";
        ob.dangerouslyUseHTMLString = true;
        ob.message +=
          '<span class="more-til" onclick="lookMessageDetail(' +
          only +
          ')">显示详情</span>';
        ob.message += '<div class="more-detail">';
        ob.message += '<div class="more-left">' + obj.msg + "</div>";
        ob.message +=
          '<div class="more-right">请求时间：' + obj.time + "</div>";
        ob.message += "</div>";
      } catch (e) {
        ob.customClass += " message-more-new";
        ob.dangerouslyUseHTMLString = true;
        ob.message +=
          '<span class="more-til" onclick="lookMessageDetail(' +
          only +
          ')">显示详情</span>';
        ob.message += '<div class="more-detail">';
        ob.message += param.data;
        ob.message += "</div>";
      }
      setTimeout(() => {
        Message(ob);
      });
      return false;
    }
    if (param.data) {
      ob.customClass += " message-more-new";
      ob.dangerouslyUseHTMLString = true;
      ob.message +=
        '<span class="more-til" onclick="lookMessageDetail(' +
        only +
        ')">显示详情</span>';
      ob.message += '<div class="more-detail">';
      if (typeof param.data === "string") {
        ob.message += param.data;
      } else {
        ob.message += '<div class="more-left">' + param.data[0] + "</div>";
        ob.message += '<div class="more-right">' + param.data[1] + "</div>";
      }
      ob.message += "</div>";
    }
    setTimeout(() => {
      Message(ob);
    });
  }
  static socketClose() {
    if (window.socket1) {
      window.socket1.close();
      window.socket1 = null;
    }
    if (window.socket2) {
      window.socket2.close();
      window.socket2 = null;
    }
    clearInterval(window.socketKeep);
    window.socketKeep = null;
    store.dispatch("clearSocketMsg");
  }
  static jumpMenu(vue, e, _blank, successFn) {
    //跳转链接
    let href = window.location.href;
    href = href.substring(href.indexOf("//") + 2, href.length);
    href = href.substring(href.indexOf("/"), href.length);
    let url;
    if (typeof e === "object") {
      _blank = e.blank || _blank;
      url = this.getUrl(e);
    } else {
      url = e;
    }
    if (!(url && href !== url)) {
      return false;
    }
    if (!_blank) {
      vue.$router.push(
        {
          path: url,
        },
        () => {
          if (successFn) {
            successFn();
          }
        }
      );
    } else {
      _blank = vue.$router.resolve(url);
      window.open(_blank.href, "_blank");
    }
  }
  static getUrl(e) {
    let url = e.url;
    let p = "";
    if (e.params) {
      Object.keys(e.params).forEach(function (key) {
        p += "&" + key + "=" + e.params[key];
      });
    }
    if (p) {
      if (!url.includes("?")) {
        url += "?";
      }
      if (!url.split("?")[1]) {
        p = p.replace("&", "");
      }
      url += p;
    }
    return url;
  }
  //判断字符是否为空
  static isEmpty(str) {
    return (
      typeof str === "undefined" || str === null || str === "" || str === " "
    );
  }
  //判断字符是否为空
  static haveLoginInfo($loginInfo) {
    return (
      $store.get("$loginInfo") &&
      JSON.stringify($loginInfo) !== "{}" &&
      $store.get("$loginInfo")
    );
  }
}

class DateFormat {
  static get(val) {
    return this.getDayStr(val) + " " + "00:00:00";
  }
  static getDayStr(val) {
    const date = val ? new Date(val) : new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    return [year, month, day].join("-");
  }
  static utcTimeToStrTime(UTCDateString) {
    if (!UTCDateString) {
      return "-";
    }
    let time = UTCDateString.replace(/T/g, " ");
    time = time.split(".")[0];
    return time;
  }
  static getAll(row, column) {
    const val = row[column.property];
    if (val === undefined) {
      return "";
    }
    const date = new Date(val); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    const y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var M = date.getMinutes();
    M = M < 10 ? "0" + M : M;
    var s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    return y + "-" + m + "-" + d + " " + "" + h + ":" + M + ":" + s;
  }
  static now(t) {
    const dataObj = this.getData(t);
    return (
      dataObj.y +
      "-" +
      dataObj.m +
      "-" +
      dataObj.d +
      " " +
      dataObj.hour +
      ":" +
      dataObj.min +
      ":" +
      dataObj.seconds
    );
  }
  static onlyStr() {
    const dataObj = this.getData();
    return (
      "" +
      dataObj.y +
      dataObj.m +
      dataObj.d +
      dataObj.hour +
      dataObj.min +
      dataObj.seconds +
      dataObj.milliseconds
    );
  }

  /**
   * 生成日期的提共通,都调这个减少代码重复率
   */
  static getData(t) {
    const val = t || new Date();
    const y = val.getFullYear();
    let m = val.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = val.getDate();
    d = d < 10 ? "0" + d : d;
    let hour = val.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    let min = val.getMinutes();
    min = min < 10 ? "0" + min : min;
    let seconds = val.getSeconds();
    seconds = seconds < 10 ? "0" + seconds : seconds;
    let milliseconds = ("000" + val.getMilliseconds()).substr(-3);
    return {
      y: y,
      m: m,
      d: d,
      hour: hour,
      min: min,
      seconds: seconds,
      milliseconds: milliseconds,
    };
  }
}
class $c {
  /**
   * @action 查询条件显示隐藏
   */
  static pageOut() {
    const _ref = document.querySelector(".page-out");
    if (_ref && _ref.childNodes.length > 0) {
      _ref.style.display = "none";
      let showStr = "";
      showStr += "    展开";
      showStr += '    <i class="el-icon-caret-bottom"></i>';
      let closeStr = "";
      closeStr += "    收起";
      closeStr += '    <i class="el-icon-caret-top"></i>';

      let str = "";
      str += '<div class="page-in-btn-more">';
      str += "  <span>";
      str += showStr;
      str += "  </span>";
      str += "</div>";
      _ref.insertAdjacentHTML("afterend", str);
      let clickFlag = false;
      const _refClick = document.querySelector(".page-in-btn-more");
      _refClick.addEventListener("click", function () {
        clickFlag = !clickFlag;
        if (clickFlag) {
          _ref.style.display = "block";
          _refClick.children[0].innerHTML = closeStr;
        } else {
          _ref.style.display = "none";
          _refClick.children[0].innerHTML = showStr;
        }
      });
    }
  }
  /**
   * @action 计算精度丢失 加
   */
  static Add(arg1, arg2) {
    var r1, r2, m;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  }
  /**
   * @action 计算精度丢失 减
   */
  static Sub(arg1, arg2) {
    var r1, r2, m, n;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // 动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  }

  /**
   * @action 计算精度丢失 乘
   */
  static Mul(arg1, arg2) {
    if (arg1 == null || arg2 == null) {
      return null;
    }
    const obj = this.numberProcessing(arg1, arg2);
    return (obj.n1 * obj.n2) / Math.pow(10, obj.r1 + obj.r2);
  }

  /**
   * @action 计算精度丢失 除
   */
  static Div(arg1, arg2) {
    const obj = this.numberProcessing(arg1, arg2);
    return (obj.n1 / obj.n2) * Math.pow(10, obj.r2 - obj.r1);
  }
  static numberProcessing(arg1, arg2) {
    var n1, n2;
    var r1, r2; // 小数位数
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    n1 = Number(arg1.toString().replace(".", ""));
    n2 = Number(arg2.toString().replace(".", ""));
    return {
      r1: r1,
      r2: r2,
      n1: n1,
      n2: n2,
    };
  }
  /**
   * @action 保留小数位数
   * @params arg1 数
   * @params arg2 保留位数
   */
  static Fixed(arg1, arg2) {
    arg1 = Number(arg1);
    arg2 = Number(arg2 || 0);
    let n = this.Mul(arg1, Math.pow(10, arg2));
    n = this.Div(parseInt(n), Math.pow(10, arg2));
    return n;
  }
}

/**
 * 大屏
 */
class BigScreen {
  /**
   * @action fitBigScreen 大屏自适应
   * @param v: 绑定元素, 例: .abc #abc, 必须
   * @param width: 原尺寸宽度, 默认元素宽度, 可选
   * @param height: 原尺寸高度, 默认元素高度, 可选
   * @param maxWidth: 最大缩放宽度,超过不缩放,默认=width, 可选
   * @param maxHeight: 最大缩放高度,超过不缩放,默认=height, 可选
   * @param scale: 比例尺, fit: 自适应等比缩放 , full: 铺满全屏, 默认full, 可选
   * @param float: 缩放浮动, left: 左边, right: 右边, bottom: 下边, scale=fit时生效 ,可选
   */
  static fit(_params) {
    this.init(_params);
    $(window).resize(() => {
      this.init(_params);
    });
  }
  static init(_params) {
    let $t = $(_params.v);
    let $p = $t.parent();
    _params.scale = _params.scale || "full";
    _params.width = parseInt(_params.width || $t.css("width"));
    _params.height = parseInt(_params.height || $t.css("height"));
    _params.vw = _params.width;
    _params.vh = _params.height;
    _params.pw = $p.width();
    _params.ph = $p.height();
    _params.mw = _params.maxWidth;
    _params.mh = _params.maxHeight;
    if (_params.mw && _params.mw < _params.pw) {
      _params.vw = _params.pw;
    }
    if (_params.mh && _params.mh < _params.ph) {
      _params.vh = _params.ph;
    }

    if (!_params.callBack) {
      _params.callBack = () => {
        return false;
      };
    }

    this.count(_params);
  }
  static count(_params) {
    let $t = $(_params.v);
    let $p = $t.parent();
    let s = _params.scale;
    let f = _params.float;
    let vw = _params.vw;
    let vh = _params.vh;
    let pw = _params.pw;
    let ph = _params.ph;

    $t.css({
      display: "block",
      overflow: "hidden",
      position: "absolute",
      width: vw,
      height: vh,
    })
      .parent()
      .css({
        overflow: "hidden",
      });
    let fw = pw;
    let fh = ph;
    if (s === "fit") {
      if (pw / ph > vw / vh || f === "left" || f === "right") {
        fh = ph;
        fw = (ph / vh) * vw;
      } else {
        fw = pw;
        fh = (pw / vw) * vh;
      }
    }
    let sx = fw / vw;
    let sy = fh / vh;
    let tx = (pw - vw) / 2 + "px";
    let ty = (ph - vh) / 2 + "px";
    if (s === "fit" && f === "left") {
      tx = (fw - vw) / 2 + "px";
    }
    if (s === "fit" && f === "right") {
      tx = pw - vw + (vw - fw) / 2 + "px";
    }
    if (s === "fit" && f === "bottom") {
      ty = ph - vh + (vh - fh) / 2 + "px";
    }
    let ppo = $p.css("position");
    if (ppo != "absolute" && ppo != "fixed") {
      $p.css({
        position: "relative",
      });
    }
    $t.css({
      top: ty,
      left: tx,
      transform: "scale(" + sx + ", " + sy + ")",
    });
    _params.callBack(sx, sy);
  }
}

/*
 *@param 请求的json对象
 *@return 返回转换为get请求形式的字符串
 */
function parseQueryParams(url) {
  const urlParams = new URLSearchParams(url.split("?")[1] || "");
  const params = {};

  for (const [key, value] of urlParams.entries()) {
    params[key] = value;
  }

  return params;
}

export {
  PAGE_SIZE,
  PAGE_SIZES,
  $v,
  DateFormat,
  $getUrlParam,
  $c,
  $store,
  $session,
  $cookie,
  urlSystem,
  urlVideo,
  urlEvent,
  BigScreen,
  videoStreamType,
  parseQueryParams,
};
